// 销售订单管理API服务
import axios from 'axios'
import { getErrorMessage } from '@/utils/error'
import { getSalesOrderApiUrl } from '@/config/apiConfig'
import type {
    CreateSalesOrderCommand,
    UpdateSalesOrderCommand,
    DeleteSalesOrderCommand,
    GetSalesOrderListQuery,
    GetSalesOrderByIdQuery,
    SalesOrderListResponse,
    SalesOrderDetailResponse,
    OperationResultResponse,
    CreateSalesOrderResponse,
    ResultCode,
    SimplePaged,
    APIResult,
    APIPageing,
    SalesOrderQueryOutput
} from '@/types/salesOrder'

// 将对象键名转换为camelCase（递归）
function toCamelCaseKey(key: string) {
    return key.charAt(0).toLowerCase() + key.slice(1)
}
function deepCamelize<T = any>(input: any): T {
    if (Array.isArray(input)) {
        return input.map(deepCamelize) as any
    }
    if (input && typeof input === 'object') {
        const obj: any = {}
        for (const k of Object.keys(input)) {
            const v = (input as any)[k]
            obj[toCamelCaseKey(k)] = deepCamelize(v)
        }
        return obj
    }
    return input
}

// 创建axios实例
const salesOrderApiClient = axios.create({
    baseURL: getSalesOrderApiUrl(),
    timeout: 10000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 添加请求拦截器
salesOrderApiClient.interceptors.request.use(
    (config) => {
        console.log('发送请求:', config.method?.toUpperCase(), config.url, config.params || config.data)
        return config
    },
    (error) => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

// 添加响应拦截器
salesOrderApiClient.interceptors.response.use(
    (response) => {
        console.log('收到响应:', response.status, response.data)
        return response
    },
    (error) => {
        console.error('响应错误:', error.response?.status, error.response?.data || error.message)
        if (error.response) {
            // 服务器返回错误状态码
            const { status, data } = error.response
            switch (status) {
                case 400:
                    throw new Error(data?.message || '请求参数错误')
                case 401:
                    throw new Error('未授权，请重新登录')
                case 403:
                    throw new Error('禁止访问')
                case 404:
                    throw new Error('请求的资源不存在')
                case 500:
                    throw new Error(data?.message || '服务器内部错误')
                default:
                    throw new Error(data?.message || `请求失败 (${status})`)
            }
        } else if (error.request) {
            // 请求已发出但没有收到响应
            throw new Error('网络连接失败，请检查网络设置')
        } else {
            // 请求配置错误
            throw new Error('请求配置错误')
        }
    }
)

function normalizeApiResult<T>(raw: any): { code: ResultCode; message: string; data: T } {
    try {
        // 处理axios响应结构
        const responseData = raw?.data || raw

        // 检查是否是分页数据（后端直接返回APIPageing<T>）
        if (responseData?.pageData !== undefined || responseData?.PageData !== undefined) {
            const paged = responseData?.pageData ?? responseData?.PageData
            const camel = {
                code: responseData?.code ?? responseData?.Code ?? ResultCode.Fail,
                message: responseData?.message ?? responseData?.Message ?? '',
                totalCount: responseData?.totalCount ?? responseData?.TotalCount ?? 0,
                pageCount: responseData?.pageCount ?? responseData?.PageCount ?? 0,
                pageData: deepCamelize(paged)
            } as any
            return { code: camel.code, message: camel.message, data: camel }
        }

        // 检查是否是APIPageing类型（继承自APIResult，直接包含分页数据）
        if (responseData?.pageData !== undefined || responseData?.PageData !== undefined) {
            // 这是APIPageing类型，直接返回
            return {
                code: responseData?.code ?? responseData?.Code ?? ResultCode.Fail,
                message: responseData?.message ?? responseData?.Message ?? '',
                data: responseData as T
            }
        }

        // 标准API结果结构
        const data = responseData?.data ?? responseData?.Data
        return {
            code: responseData?.code ?? responseData?.Code ?? ResultCode.Fail,
            message: responseData?.message ?? responseData?.Message ?? '',
            data: deepCamelize(data)
        }
    } catch (error) {
        console.error('解析API结果失败:', error)
        return {
            code: ResultCode.Fail,
            message: '解析响应数据失败',
            data: null as any
        }
    }
}

// 销售订单API服务
export const salesOrderApi = {
    /**
     * 获取销售订单列表
     */
    async getList(query: GetSalesOrderListQuery): Promise<APIPageing<SalesOrderQueryOutput>> {
        try {
            console.log('发送请求: GET /api/SalesOrder/GetSalesOrders', query)
            const response = await salesOrderApiClient.get('/api/SalesOrder/GetSalesOrders', { params: query })
            console.log('收到响应:', response.status, response.data)

            // 后端直接返回APIPageing<T>，不需要APIResult包装
            const result = response.data
            console.log('解析后的结果:', result)
            return result
        } catch (error) {
            console.error('API请求失败:', error)
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 根据ID获取销售订单详情
     */
    async getById(id: number): Promise<APIResult<SalesOrderDetailResponse>> {
        try {
            const response = await salesOrderApiClient.get(`/api/SalesOrder/GetSalesOrderById/${id}`)
            return normalizeApiResult(response)
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 创建销售订单
     */
    async create(command: CreateSalesOrderCommand): Promise<CreateSalesOrderResponse> {
        try {
            const response = await salesOrderApiClient.post('/api/SalesOrder/AddSalesOrder', command)
            return normalizeApiResult(response)
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 更新销售订单
     */
    async update(command: UpdateSalesOrderCommand): Promise<OperationResultResponse> {
        try {
            const response = await salesOrderApiClient.put(`/api/SalesOrder/UpdateSalesOrder/${command.id}`, command)
            return normalizeApiResult(response)
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 删除销售订单
     */
    async delete(id: number): Promise<OperationResultResponse> {
        try {
            const response = await salesOrderApiClient.delete(`/api/SalesOrder/DeleteSalesOrder/${id}`)
            return normalizeApiResult(response)
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 更新销售订单状态
     */
    async updateStatus(id: number, orderStatus: string): Promise<OperationResultResponse> {
        try {
            const response = await salesOrderApiClient.put(`/api/SalesOrder/UpdateSalesOrderStatus/${id}/status`, orderStatus)
            return normalizeApiResult(response)
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 插入测试数据
     */
    async insertTestData(): Promise<OperationResultResponse> {
        try {
            const response = await salesOrderApiClient.post('/api/SalesOrder/InsertTestData')
            return normalizeApiResult(response)
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    },

    /**
     * 测试API连接
     */
    async testConnection(): Promise<OperationResultResponse> {
        try {
            const response = await salesOrderApiClient.get('/api/SalesOrder/GetSalesOrders', {
                params: { pageIndex: 1, pageSize: 1 }
            })
            // 后端返回APIPageing类型，转换为OperationResultResponse
            const data = response.data
            return {
                code: data.code || data.Code || ResultCode.Fail,
                message: data.message || data.Message || '连接测试成功',
                data: data
            }
        } catch (error) {
            throw new Error(getErrorMessage(error))
        }
    }
}

export default salesOrderApi 